'use strict';
const Controller = require('egg').Controller;
const AlipaySdk = require('alipay-sdk').default;
const AlipayFormData = require('alipay-sdk/lib/form').default;
const alipayConfig = require('../../config/alipay');
const axios = require('axios');
const alipaySdk = new AlipaySdk(alipayConfig);
class AlipayController extends Controller {
  // 支付宝跳转页面
  async payment() {
    const { ctx } = this;
    const formData = new AlipayFormData();
    const orderInfo = ctx.request.body;
    // 支付这一步应该是从数据库中查到的订单编号
    // console.log(orderInfo);
    formData.setMethod('get');
    formData.addField('returnUrl', 'http://localhost:8080'); // 支付成功返回的界面
    formData.addField('notifyUrl', 'http://localhost:7001/notify');// 异步回调
    formData.addField('bizContent', {
      outTradeNo: orderInfo.orderID, // 订单号
      totalAmount: orderInfo.total_price, // 订单金额
      subject: orderInfo.room_title, // 订单标题
      body: '酒店预订房价', // 订单描述
      productCode: 'FAST_INSTANT_TRADE_PAY',
    });
    // 调用支付宝沙箱的跳转接口
    const payUrl = await alipaySdk.exec('alipay.trade.page.pay', {}, {
      formData,
    });
    ctx.body = {
      code: 200,
      message: '订单创建成功，即将跳转支付页面',
      payUrl,
    };
    this.queryOrderAlipay(orderInfo.orderID);
  }
  // 查询订单是否支付成功
  async queryOrderAlipay() {
    const formData = new AlipayFormData();
    const ID = this.ctx.request.query.orderID;
    const updateOrderState = await this.app.model.Reservation.findOne({ where: { orderID: ID } });
    // const updateOrderState = await this.app.model.Reservation.findOne({ where: { orderID } });
    formData.setMethod('get');
    formData.addField('bizContent', {
      outTradeNo: ID, // 通过订单id进行查询
      // outTradeNo: orderID,
    });
    // 调用支付宝沙箱的查询接口

    const codeResult = await alipaySdk.exec('alipay.trade.query', {}, {
      formData,
    });
    await axios({
      url: codeResult,
      methods: 'get',
    }).then(async resStatus => {
      // console.log(resStatus.data.alipay_trade_query_response);
      const r = resStatus.data.alipay_trade_query_response;
      if (r.code === '10000') { // 接口调用成功
        switch (r.trade_status) {
          case 'WAIT_BUYER_PAY':
            await updateOrderState.update({ orderState: 1 });
            this.ctx.body = {
              code: 200,
              status: 'wait',
              msg: '交易创建，等待买家付款',
            };
            break;
          case 'TRADE_CLOSED':
            await updateOrderState.update({ orderState: 1 });
            this.ctx.body = {
              code: 200,
              status: 'wait',
              msg: '未付款或交易超时',
            };
            break;
          case 'TRADE_SUCCESS':
            await updateOrderState.update({ orderState: 2 });
            this.ctx.body = {
              code: 200,
              status: 'success',
              msg: '交易支付成功',
            };
            break;
          case 'TRADE_FINISHED':
            this.ctx.body = {
              code: 200,
              status: 'FINISHED',
              msg: '交易结束，不可退款',
            };
            break;
          default:
            this.ctx.body = {
              code: 40004,
              status: 'NoExist',
              msg: '查询的交易状态不存在',
            };
            break;
        }
      } else if (r.code === '40004') {
        this.ctx.body = {
          code: 40004,
          status: 'no-exist',
          msg: '未支付或交易不存在',
        };
      }
    }).catch(err => {
      this.ctx.body = {
        code: 500,
        msg: '查询失败',
        err,
      };
    });


  }
  // d的当面付返回一个二维码
  async createQrCode() {
    const { ctx } = this;
    const data = ctx.request.body;
    // console.log(data);
    const qrCodeUrl = await ctx.service.alipay.createQrCode(data);
    // console.log(qrCodeUrl);
    if (qrCodeUrl) {
      ctx.body = {
        code: 200,
        data: qrCodeUrl,
      };
    } else {
      ctx.body = {
        code: 500,
        msg: '生成二维码失败',
      };
    }
  }

}
module.exports = AlipayController;
